package com.chhuang.uresource.service.impl;

import java.io.File;
import java.util.List;

import org.apache.commons.httpclient.URI;
import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.chhuang.core.bean.QueryBean;
import com.chhuang.core.service.impl.BaseServiceImpl;
import com.chhuang.uresource.bean.UResourceQueryBean;
import com.chhuang.uresource.mapper.UResourceMapper;
import com.chhuang.uresource.po.UResource;
import com.chhuang.uresource.po.UResourceExample;
import com.chhuang.uresource.service.IUResourceService;
import com.chhuang.uresource.thread.DeleteResourceFileThread;
import com.chhuang.utils.Assert;

/**
* UResource ServiceImpl
* @author ChHuang
* @date Fri Mar 02 09:41:12 CST 2018
*/
@Service
public class UResourceServiceImpl extends BaseServiceImpl<UResourceMapper, UResource> implements IUResourceService {
	private static final Log log = LogFactory.getLog(UResourceServiceImpl.class);
	
	@Autowired
	private UResourceMapper uResourceMapper;

	@Override
	public QueryBean<UResource> seniorQuery(QueryBean<UResource> queryBean) throws Exception {
		UResourceQueryBean poQueryBean = (UResourceQueryBean)queryBean;
		UResourceExample example = new UResourceExample();
		
		if(poQueryBean.isAnd()){//全部是与条件
			UResourceExample.Criteria criteria = example.createCriteria();
			if(Assert.isValidString(poQueryBean.getResourceId())){
				criteria.andResourceIdEqualTo(poQueryBean.getResourceId());
			}
			if(Assert.isValidString(poQueryBean.getResourceName())){
				criteria.andResourceNameLike("%"+poQueryBean.getResourceName()+"%");
			}
			if(Assert.isValidString(poQueryBean.getResourceType())){
				criteria.andResourceTypeLike("%"+poQueryBean.getResourceType()+"%");
			}
			if(poQueryBean.getResourceLength() != null){
				criteria.andResourceLengthEqualTo(poQueryBean.getResourceLength());
			}
			if(Assert.isValidString(poQueryBean.getResourceIntroduction())){
				criteria.andResourceIntroductionLike("%"+poQueryBean.getResourceIntroduction()+"%");
			}
			if(Assert.isValidString(poQueryBean.getSearchKeyWords())){
				criteria.andSearchKeyWordsLike("%"+poQueryBean.getSearchKeyWords()+"%");
			}
			if(Assert.isValidString(poQueryBean.getResourceAuthorId())){
				criteria.andResourceAuthorIdLike("%"+poQueryBean.getResourceAuthorId()+"%");
			}
			if(Assert.isValidString(poQueryBean.getResourcePath())){
				criteria.andResourcePathLike("%"+poQueryBean.getResourcePath()+"%");
			}
			if(poQueryBean.getPathType() != null){
				criteria.andPathTypeEqualTo(poQueryBean.getPathType());
			}
			if(poQueryBean.getDownloadAmount() != null){
				criteria.andDownloadAmountEqualTo(poQueryBean.getDownloadAmount());
			}
			if(poQueryBean.getCreateTime() != null){
				criteria.andCreateTimeEqualTo(poQueryBean.getCreateTime());
			}
			if(poQueryBean.getModifyTime() != null){
				criteria.andModifyTimeEqualTo(poQueryBean.getModifyTime());
			}
		}else{//全部是或条件
			if(Assert.isValidString(poQueryBean.getResourceId())){
				example.or().andResourceIdEqualTo(poQueryBean.getResourceId());
			}
			if(Assert.isValidString(poQueryBean.getResourceName())){
				example.or().andResourceNameLike("%"+poQueryBean.getResourceName()+"%");
			}
			if(Assert.isValidString(poQueryBean.getResourceType())){
				example.or().andResourceTypeLike("%"+poQueryBean.getResourceType()+"%");
			}
			if(poQueryBean.getResourceLength() != null){
				example.or().andResourceLengthEqualTo(poQueryBean.getResourceLength());
			}
			if(Assert.isValidString(poQueryBean.getResourceIntroduction())){
				example.or().andResourceIntroductionLike("%"+poQueryBean.getResourceIntroduction()+"%");
			}
			if(Assert.isValidString(poQueryBean.getSearchKeyWords())){
				example.or().andSearchKeyWordsLike("%"+poQueryBean.getSearchKeyWords()+"%");
			}
			if(Assert.isValidString(poQueryBean.getResourceAuthorId())){
				example.or().andResourceAuthorIdLike("%"+poQueryBean.getResourceAuthorId()+"%");
			}
			if(Assert.isValidString(poQueryBean.getResourcePath())){
				example.or().andResourcePathLike("%"+poQueryBean.getResourcePath()+"%");
			}
			if(poQueryBean.getPathType() != null){
				example.or().andPathTypeEqualTo(poQueryBean.getPathType());
			}
			if(poQueryBean.getDownloadAmount() != null){
				example.or().andDownloadAmountEqualTo(poQueryBean.getDownloadAmount());
			}
			if(poQueryBean.getCreateTime() != null){
				example.or().andCreateTimeEqualTo(poQueryBean.getCreateTime());
			}
			if(poQueryBean.getModifyTime() != null){
				example.or().andModifyTimeEqualTo(poQueryBean.getModifyTime());
			}
		}
		
		poQueryBean.setItemCount(uResourceMapper.countByExample(example));//总记录数
		if(poQueryBean.getItemCount()>0){//计算总页数
			poQueryBean.setPageCount(poQueryBean.getItemCount()/poQueryBean.getPageSize()+
					(int)(poQueryBean.getItemCount()%poQueryBean.getPageSize()>0?1:0));
			if(poQueryBean.getPageCount()>=poQueryBean.getPageNum()){
				if(Assert.isValidString(poQueryBean.getOrderBy())){//排序
					example.setOrderByClause(poQueryBean.getOrderBy()+" "+poQueryBean.getOrder());
				}
				//分页
				example.setOffset((poQueryBean.getPageNum()-1)*poQueryBean.getPageSize());
				example.setLimit(poQueryBean.getPageSize());
				poQueryBean.setResult(uResourceMapper.selectByExample(example));
			}
		}
		
		return poQueryBean;
	}

	@Override
	public void deleteByPrimaryKeys(String[] resourceIds) throws Exception {
		for(String resourceId : resourceIds) {
    		UResource resource = uResourceMapper.selectByPrimaryKey(resourceId);
    		if(resource!=null) {
    			boolean deleteFileSuccess = true;
    			if(resource.getPathType()==0 && Assert.isValidString(resource.getResourcePath())) {
    				File file = new File(resource.getResourcePath());
    				if(file.exists()) {
    					deleteFileSuccess = FileUtils.deleteQuietly(file);
    				}
    			}
    			if(deleteFileSuccess) {
	    			log.info("“"+resource.getResourceName()+"” 文件删除结果:" + deleteFileSuccess);
	    			uResourceMapper.deleteByPrimaryKey(resourceId);
    			}else {
    				new Thread(new DeleteResourceFileThread(resource)).start();
    			}
    		}else {
    			log.info("编号：“"+resourceId+"” 资源不存在。");
    		}
		}
	}

	@Override
	public List<UResource> findAll() throws Exception {
		return uResourceMapper.selectAll();
	}

	@Override
	public void arrangement() throws Exception {
		List<UResource> resources = uResourceMapper.selectAll();
		if(Assert.isValidCollection(resources)){
			for(UResource res : resources){
				if(Assert.isValidString(res.getResourcePath())){
					URI uri = new URI(res.getResourcePath(), false);
					String scheme = uri.getScheme();
					//0自己的资源，1其它网站地址如百度网盘分享地址，2电驴，3磁力，4迅雷
					if("ed2k".equals(scheme)){
						res.setPathType(2);
						uResourceMapper.updateByPrimaryKey(res);
					}else if("magnet".equals(scheme)){
						res.setPathType(3);
						uResourceMapper.updateByPrimaryKey(res);
					}else if("thunder".equals(scheme)){
						res.setPathType(4);
						uResourceMapper.updateByPrimaryKey(res);
					}
				}
			}
		}
	}
	
}